package com.xiangxiangjd.aircraftanalysis.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.xiangxiangjd.aircraftanalysis.controller.helper.$;
import com.xiangxiangjd.aircraftanalysis.utils.excel.ExportExcel;
import com.xiangxiangjd.aircraftanalysis.utils.excel.ImportExcel;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import com.xiangxiangjd.aircraftanalysis.bean.result.ResultPage;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xiangxiangjd.aircraftanalysis.service.EngineService;
import com.xiangxiangjd.aircraftanalysis.bean.Engine;
import com.xiangxiangjd.aircraftanalysis.controller.model.ApiResultModel;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 肖守凯
 * @since 2021-05-10
 */
@Controller
@RequestMapping("/aircraftanalysis/engine")
@Slf4j
public class EngineController extends BaseController {


    /**
     * 主页面
     */
    @RequestMapping("admin/main.html")
    public String main() {
        return "Engine/EngineMain";
    }

    /**
     * 添加页面跳转
     *
     * @return 返回页面
     */
    @RequestMapping(value = "admin/addEngineHtml")
    public String addEngineHtml() {
        return "Engine/EngineAdd";
    }

    /**
     * 编辑页面跳转
     *
     * @param id 前端传进的参数
     * @return 返回页面
     */
    @RequestMapping(value = "admin/editEngineHtml")
    public String editEngineHtml(String id, Model model) {

        model.addAttribute("engine", setUrl(engineService.selectEngineByIdEngine(id)));
        return "Engine/EngineEdit";
    }

    /**
     * 查看页面跳转
     *
     * @param id 前端传进的参数
     * @return 返回页面
     */
    @RequestMapping(value = "admin/showEngineHtml")
    public String showEngineHtml(String id, Model model) {

        Engine engine = engineService.selectEngineByIdEngine(id);


        model.addAttribute("engine", setUrl(engine));


        return "Engine/EngineShow";
    }

    private Engine setUrl(Engine engine) {
        String[] name = engine.getName().split("==");
        engine.setName(name[0]);
        if (name.length > 1) {
            engine.setNameUrl(name[1]);
        }

        String[] purpose = engine.getPurpose().split("==");
        engine.setPurpose(purpose[0]);
        if (purpose.length > 1) engine.setPurposeUrl(purpose[1]);


        String[] requirement = engine.getRequirement().split("==");
        engine.setRequirement(requirement[0]);
        if (requirement.length > 1) engine.setRequirementUrl(requirement[1]);


        String[] function = engine.getFunction().split("==");
        engine.setFunction(function[0]);
        if (function.length > 1) engine.setFunctionUrl(function[1]);

        String[] performance = engine.getPerformance().split("==");
        engine.setPerformance(performance[0]);
        if (performance.length > 1) engine.setPerformanceUrl(performance[1]);

        String[] Interface = engine.getInterface().split("==");
        engine.setInterface(Interface[0]);
        if (Interface.length > 1) engine.setInterfaceUrl(Interface[1]);

        String[] weight = engine.getWeight().split("==");
        engine.setWeight(weight[0]);
        if (weight.length > 1) engine.setWeightUrl(weight[1]);

        String[] size = engine.getSize().split("==");
        engine.setSize(size[0]);
        if (size.length > 1) engine.setSizeUrl(size[1]);

        String[] powerSupply = engine.getPowerSupply().split("==");
        engine.setPowerSupply(powerSupply[0]);
        if(powerSupply.length>1)  engine.setPowerSupplyUrl(powerSupply[1]);

        String[] life = engine.getLife().split("==");
        engine.setLife(life[0]);
       if(life.length>1) engine.setLifeUrl(life[1]);

        String[] reliability = engine.getReliability().split("==");
        engine.setReliability(reliability[0]);
        if(reliability.length>1) engine.setReliabilityUrl(reliability[1]);

        String[] maintainability = engine.getMaintainability().split("==");
        engine.setMaintainability(maintainability[0]);
       if(maintainability.length>1)  engine.setMaintainabilityUrl(maintainability[1]);

        String[] testability = engine.getTestability().split("==");
        engine.setTestability(testability[0]);
        if(testability.length>1) engine.setTestabilityUrl(testability[1]);

        String[] security = engine.getSecurity().split("==");
        engine.setSecurity(security[0]);
        if(security.length>1) engine.setSecurityUrl(security[1]);

        String[] supportability = engine.getSupportability().split("==");
        engine.setSupportability(supportability[0]);
       if(supportability.length>1) engine.setSupportabilityUrl(supportability[1]);

        String[] Environment = engine.getEnvironment().split("==");
        engine.setEnvironment(Environment[0]);
       if(Environment.length>1) engine.setEnvironmentUrl(Environment[1]);

        String[] Electromagnetism = engine.getElectromagnetism().split("==");
        engine.setElectromagnetism(Electromagnetism[0]);
        if(Electromagnetism.length>1) engine.setElectromagnetismUrl(Electromagnetism[1]);

        String[] metering = engine.getMetering().split("==");
        engine.setMetering(metering[0]);
       if(metering.length>1) engine.setMeteringUrl(metering[1]);

        String[] packingTransport = engine.getPackingTransport().split("==");
        engine.setPackingTransport(packingTransport[0]);
       if(packingTransport.length>1) engine.setPackingTransportUrl(packingTransport[1]);

        return engine;
    }


    /**
     * 分页查询Engine
     *
     * @param page   页码
     * @param limit  查几条
     * @param engine 前端传进的参数
     * @return 返回统一分页信息
     */
    @RequestMapping(value = "admin/findEngineByPage")
    @ResponseBody
    public ResultPage findEngineByPage(Integer page, Integer limit, Engine engine) {
        return engineService.findEngineByPage(page, limit, engine);
    }

    /**
     * 添加Engine
     *
     * @param engine 前端传进的参数
     * @return 返回统一信息
     */
    @RequestMapping(value = "admin/addEngine")
    @ResponseBody
    public ApiResultModel saveEngine(Engine engine) {

        List<Engine> list = engineService.list(new LambdaQueryWrapper<Engine>()
                .eq(Engine::getName, engine.getName()));

        if (list.size() > 0) return $.error("该设备已存在！");


        return engineService.addEngine(engine);
    }

    /**
     * 编辑Engine
     *
     * @param engine 前端传进的参数
     * @return 返回统一信息
     */
    @RequestMapping(value = "admin/editEngine")
    @ResponseBody
    public ApiResultModel editEngine(Engine engine) {






        return engineService.editEngine(engine);
    }


    /**
     * 删除Engine
     *
     * @param ids 前端传进的ID
     * @return 返回统一信息
     */
    @RequestMapping(value = "admin/delEngine", method = RequestMethod.GET)
    @ResponseBody
    public ApiResultModel delEngine(@RequestParam("datas[]") ArrayList ids) {


        return engineService.delEngines(ids);
    }


    /**
     * 下载导入的ex 的表格
     */
    @ResponseBody
    @RequestMapping(value = "get/template")
    public void importFileTemplate(HttpServletResponse response) throws IOException {
        log.info("开始下载导入的ex 的表格****");

        String fileName = "飞机修理任务级别分析统计系统.xlsx";
        List<Engine> list = Lists.newArrayList();
        new ExportExcel("飞机修理任务级别分析统计系统", Engine.class, 1).setDataList(list).write(response, fileName).dispose();

    }


    /**
     * 导入Excel   批量导入数据
     *
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "Import")
    public ApiResultModel importFile(@RequestParam("file") MultipartFile file) {


        log.info("开始批量导入文件!");
        if (file.isEmpty()) {
            return $.error("文件不可为空");
        }
//        System.out.println("文件类型为:" + file.getContentType());
//
        if (!file.getContentType().equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
            return $.error("文件类型必须为xlsx");
        }

        try {
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<Engine> list = ei.getDataList(Engine.class);
            /**
             * 查询名称是否有重复的
             */
            for (int i = 0; i < list.size(); i++) {

                List<Engine> list1 = engineService.list(new LambdaQueryWrapper<Engine>()
                        .eq(Engine::getName, list.get(i).getName()));
                if (list1.size() > 0) return $.error(list.get(i).getName() + "该设备已存在，请修改设备名称");
            }

            //批量插入 详细信息
            engineService.saveBatch(list);

            // 导入成功
            return $.success();

        } catch (IOException e) {
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
        } catch (InstantiationException e) {
        }

        return $.error();
    }


}
